<template>
  <div class="workspace-manager">
    <div class="workspace-header">
      <h2>工作区管理</h2>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        新建工作区
      </el-button>
    </div>

    <div class="workspace-content">
      <!-- 工作区选择器 -->
      <div class="workspace-selector">
        <h3>当前工作区</h3>
        <el-select 
          v-model="currentWorkspaceId" 
          placeholder="选择工作区"
          size="large"
          class="workspace-select"
          @change="handleWorkspaceChange"
        >
          <el-option
            v-for="workspace in workspaces"
            :key="workspace.id"
            :label="workspace.name"
            :value="workspace.id"
          >
            <span>{{ workspace.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ formatDate(workspace.created_at) }}
            </span>
          </el-option>
        </el-select>
      </div>

      <!-- 工作区详情 -->
      <div v-if="currentWorkspace" class="workspace-details">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>工作区信息</span>
              <el-button type="text" @click="editWorkspace">编辑</el-button>
            </div>
          </template>
          <div class="workspace-info">
            <p><strong>名称：</strong>{{ currentWorkspace.name }}</p>
            <p><strong>描述：</strong>{{ currentWorkspace.description || '无描述' }}</p>
            <p><strong>创建时间：</strong>{{ formatDate(currentWorkspace.created_at) }}</p>
            <p><strong>更新时间：</strong>{{ formatDate(currentWorkspace.updated_at) }}</p>
          </div>
        </el-card>
      </div>

      <!-- 分析会话列表 -->
      <div v-if="currentWorkspaceId" class="sessions-section">
        <h3>分析会话</h3>
        <el-button type="primary" size="small" @click="showCreateSessionDialog = true">
          新建会话
        </el-button>
        
        <el-table :data="sessions" style="width: 100%; margin-top: 16px">
          <el-table-column prop="name" label="会话名称" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="viewSession(row)">查看</el-button>
              <el-button type="text" size="small" @click="deleteSession(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 创建工作区对话框 -->
    <el-dialog v-model="showCreateDialog" title="创建工作区" width="500px">
      <el-form :model="createForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="createForm.name" placeholder="请输入工作区名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            placeholder="请输入工作区描述（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createWorkspace">创建</el-button>
      </template>
    </el-dialog>

    <!-- 编辑工作区对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑工作区" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="editForm.name" placeholder="请输入工作区名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            placeholder="请输入工作区描述（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateWorkspace">保存</el-button>
      </template>
    </el-dialog>

    <!-- 创建会话对话框 -->
    <el-dialog v-model="showCreateSessionDialog" title="创建分析会话" width="500px">
      <el-form :model="sessionForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="sessionForm.name" placeholder="请输入会话名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input 
            v-model="sessionForm.description" 
            type="textarea" 
            placeholder="请输入会话描述（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateSessionDialog = false">取消</el-button>
        <el-button type="primary" @click="createSession">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getWorkspaces, 
  updateWorkspace as apiUpdateWorkspace,
  getAnalysisSessions,
  createAnalysisSession,
  deleteAnalysisSession
} from '@/api'
import type { Workspace, AnalysisSession } from '../types/workspace'
import { useWorkspaceStore } from '@/stores/workspace'

// 使用全局workspace store
const workspaceStore = useWorkspaceStore()

// 响应式数据
const workspaces = ref<Workspace[]>([])
const currentWorkspaceId = ref<string>('')
const sessions = ref<AnalysisSession[]>([])
const currentSession = ref<AnalysisSession | null>(null)
const loading = ref(false)

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showCreateSessionDialog = ref(false)

// 表单数据
const createForm = ref({
  name: '',
  description: ''
})

const editForm = ref({
  name: '',
  description: ''
})

const sessionForm = ref({
  name: '',
  description: ''
})

// 计算属性
const currentWorkspace = computed(() => {
  return workspaces.value.find(ws => ws.id === currentWorkspaceId.value)
})

// 方法
const loadWorkspaces = async () => {
  try {
    loading.value = true
    const response = await getWorkspaces()
    workspaces.value = response as unknown as Workspace[]
    
    // 如果没有选中的工作区，选择第一个
    if (!currentWorkspaceId.value && workspaces.value.length > 0) {
      currentWorkspaceId.value = workspaces.value[0].id
      await loadSessions()
    }
  } catch (error) {
    ElMessage.error('加载工作区列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const loadSessions = async () => {
  if (!currentWorkspaceId.value) return
  
  try {
    const response = await getAnalysisSessions(currentWorkspaceId.value)
    sessions.value = response as unknown as AnalysisSession[]
  } catch (error) {
    ElMessage.error('加载分析会话失败')
    console.error(error)
  }
}

const handleWorkspaceChange = async () => {
  // 设置当前工作区到store
  const workspace = workspaces.value.find(w => w.id === currentWorkspaceId.value)
  if (workspace) {
    workspaceStore.currentWorkspace = workspace
  }
  await loadSessions()
}

const createWorkspace = async () => {
  if (!createForm.value.name.trim()) {
    ElMessage.warning('请输入工作区名称')
    return
  }

  try {
    const ws = await workspaceStore.createWorkspace(createForm.value.name, createForm.value.description)
    ElMessage.success('工作区创建成功')
    showCreateDialog.value = false
    createForm.value = { name: '', description: '' }
    await loadWorkspaces()
    if (ws && (ws as any).id) {
      currentWorkspaceId.value = (ws as any).id
      await handleWorkspaceChange()
    }
  } catch (error) {
    ElMessage.error('创建工作区失败')
    console.error(error)
  }
}

const editWorkspace = () => {
  if (!currentWorkspace.value) return
  
  editForm.value = {
    name: currentWorkspace.value.name,
    description: currentWorkspace.value.description || ''
  }
  showEditDialog.value = true
}

const updateWorkspace = async () => {
  if (!editForm.value.name.trim()) {
    ElMessage.warning('请输入工作区名称')
    return
  }

  try {
    await apiUpdateWorkspace(currentWorkspaceId.value, editForm.value)
    ElMessage.success('工作区更新成功')
    showEditDialog.value = false
    await loadWorkspaces()
  } catch (error) {
    ElMessage.error('更新工作区失败')
    console.error(error)
  }
}

const createSession = async () => {
  if (!sessionForm.value.name.trim()) {
    ElMessage.warning('请输入会话名称')
    return
  }

  try {
    const newSession = await createAnalysisSession({
      workspace_id: currentWorkspaceId.value,
      ...sessionForm.value
    })
    // 自动切换到新创建的会话
    workspaceStore.switchSession(newSession as unknown as AnalysisSession)
    ElMessage.success('分析会话创建成功')
    showCreateSessionDialog.value = false
    sessionForm.value = { name: '', description: '' }
    await loadSessions()
  } catch (error) {
    ElMessage.error('创建分析会话失败')
    console.error(error)
  }
}

const viewSession = (session: AnalysisSession) => {
  // 设置为当前会话
  workspaceStore.switchSession(session)
  ElMessage.success(`已切换到会话: ${session.name}`)
}

const deleteSession = async (session: AnalysisSession) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除会话 "${session.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAnalysisSession(session.id)
    ElMessage.success('会话删除成功')
    await loadSessions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除会话失败')
      console.error(error)
    }
  }
}

const getStatusType = (status: string) => {
  const types = {
    'created': '',
    'analyzing': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return (types as any)[status] || ''
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadWorkspaces()
})
</script>

<style scoped>
.workspace-manager {
  padding: 24px;
  height: 100%;
  overflow-y: auto;
}

.workspace-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.workspace-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.workspace-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.workspace-selector h3 {
  margin: 0 0 16px 0;
  color: var(--el-text-color-primary);
}

.workspace-select {
  width: 100%;
  max-width: 400px;
}

.workspace-details .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.workspace-info p {
  margin: 8px 0;
  color: var(--el-text-color-regular);
}

.sessions-section h3 {
  margin: 0 0 16px 0;
  color: var(--el-text-color-primary);
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .workspace-manager {
    padding: 16px;
  }
  
  .workspace-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .workspace-select {
    max-width: 100%;
  }
}
</style>